package repositories

import (
	"github.com/kataras/iris/v12"
	"gorm.io/gorm"
	"huanteng/web/global/application"

	"huanteng/vendors/paginate"
	"huanteng/web/models"
)

/*type RoleRepository interface {
	Create(role *models.Role)
	FindByName(name string) (role models.Role)
	RoleList(ctx iris.Context,role *[]models.Role)
	Update(id uint, user *models.Role)
	Delete(id uint)

}*/

type RoleRepository struct {
	db *gorm.DB
}

/*func NewRoleRepository (db *gorm.DB) RoleRepository{
	return &RoleRepository{
		db:db,
	}
}*/
func (a *RoleRepository)SetRole(id uint,ids []uint)error{
	tx:=application.DB.Begin()
	defer func() {
		if r:=recover();r!=nil{
			tx.Rollback()
		}
	}()
	if err:=tx.Where(&models.AdminRole{AdminID:id}).Delete(&models.AdminRole{}).Error;err!=nil{
		tx.Rollback()
		return err
	}

	if len(ids)>0{
		for _,rid:=range ids{
			if err:=tx.Create(models.AdminRole{RoleID:rid,AdminID:id}).Error;err!=nil{
				tx.Rollback()
				return err
			}
		}
	}
	return tx.Commit().Error
}

func (a *RoleRepository)GetMenuById(model models.RoleMenu,where interface{},menuIDList interface{},filed string){
	application.DB.Model(model).Where(where).Pluck(filed,menuIDList)
}

func (a *RoleRepository)AllRole() []models.Role {
	var list []models.Role
	application.DB.Order("parent_id asc").Order("sequence asc").Find(&list)
	//application.DB.Where("id = ?", id).Delete(&models.Admin{})
	return list
}

func (a *RoleRepository)Delete(ids []uint)error  {
	//事物准备
	tx:=application.DB.Begin()
	//异常延迟恢复
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	//删除角色
	if err := tx.Where("id in (?)", ids).Delete(&models.Role{}).Error; err != nil {
		tx.Rollback()
		return err
	}

	//删除角色子节点(暂不处理)
	/*if err := tx.Where("parent_id in (?)", ids).Delete(&models.Role{}).Error; err != nil {
		tx.Rollback()
		return err
	}*/

	//删除角色菜单关联表
	if err := tx.Where("role_id in (?)", ids).Delete(&models.RoleMenu{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error


	//application.DB.Where("id = ?", id).Delete(&models.Admin{})
}
func (a *RoleRepository)Update(role *models.Role)  {

	application.DB.Model(models.Role{ID:role.ID}).Updates(&role)
}


func (a *RoleRepository)RoleList(ctx iris.Context)  {
	var role []models.Role
	where:=models.Role{}

	if m:=ctx.URLParamExists("parent_id");m==true{
		parent_id:=uint(ctx.URLParamUint64("parent_id"))
		where.ParentID=&parent_id
	}

	where.Name=ctx.URLParam("name")
	//application.DB.Where(where).Preload("Menu").Scopes(paginate.Paginate(&role))
	application.DB.Where(where).Scopes(paginate.Paginate(&role))
}

func (a *RoleRepository)GetByid(id uint)(m models.Role)  {
	application.DB.Where(&models.Role{ID:id}).First(&m)
	return m
}

func (a *RoleRepository)FindByName(name string) (role models.Role)  {
	 application.DB.Where("name=?",name).First(&role)
	 return
}
func (a *RoleRepository)Create(role *models.Role) {
	application.DB.Create(role)

}

